//
//  DBNetworkMonitor.swift
//  DBCA
//
//  Created by mugua on 2024/7/2.
//

import Foundation
import Alamofire

public enum Status {
    case unknown
    case notReachable
    case wwan
    case wifi
}

typealias DBNetworkStatus = ((_ status: Status) -> ())

public class DBNetworkMonitor {
    
    public static let shared = DBNetworkMonitor()
    
    let lock = NSLock()
    
    let reachabilityManager = NetworkReachabilityManager(host: "www.apple.com")
    
    func monitorNetworkStatus(netStatus: @escaping DBNetworkStatus) {
        
        reachabilityManager?.startListening(onUpdatePerforming: { [weak self] (status) in
            self?.lock.lock()
            switch status {
            case .unknown:
                netStatus(.unknown)
            case .notReachable:
                netStatus(.notReachable)
            case .reachable(.cellular):
               
                #if targetEnvironment(macCatalyst)
                netStatus(.unknown)
                #else
                netStatus(.wwan)
                #endif

            case .reachable(.ethernetOrWiFi):
                netStatus(.wifi)
            }
            self?.lock.unlock()
        })
    }
    
    deinit {
        reachabilityManager?.stopListening()
    }
}
